import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:gap/gap.dart';
import '../animations/animation_config.dart';
import 'loading_widget.dart';

/// 高级图片组件
/// 封装cached_network_image，提供统一的图片加载体验
class AdvancedImage extends StatelessWidget {
  const AdvancedImage({
    super.key,
    required this.imageUrl,
    this.width,
    this.height,
    this.fit = BoxFit.cover,
    this.placeholder,
    this.errorWidget,
    this.borderRadius,
    this.enableMemoryCache = true,
    this.enableDiskCache = true,
    this.cacheKey,
    this.headers,
    this.fadeInDuration = AnimationConfig.medium,
    this.fadeOutDuration = AnimationConfig.fast,
    this.placeholderFadeInDuration = AnimationConfig.fast,
    this.alignment = Alignment.center,
    this.repeat = ImageRepeat.noRepeat,
    this.matchTextDirection = false,
    this.useOldImageOnUrlChange = false,
    this.color,
    this.colorBlendMode,
    this.filterQuality = FilterQuality.low,
    this.shape = BoxShape.rectangle,
    this.enableHero = false,
    this.heroTag,
    this.onTap,
    this.enableZoom = false,
  });

  final String imageUrl;
  final double? width;
  final double? height;
  final BoxFit fit;
  final Widget? placeholder;
  final Widget? errorWidget;
  final BorderRadius? borderRadius;
  final bool enableMemoryCache;
  final bool enableDiskCache;
  final String? cacheKey;
  final Map<String, String>? headers;
  final Duration fadeInDuration;
  final Duration fadeOutDuration;
  final Duration placeholderFadeInDuration;
  final Alignment alignment;
  final ImageRepeat repeat;
  final bool matchTextDirection;
  final bool useOldImageOnUrlChange;
  final Color? color;
  final BlendMode? colorBlendMode;
  final FilterQuality filterQuality;
  final BoxShape shape;
  final bool enableHero;
  final String? heroTag;
  final VoidCallback? onTap;
  final bool enableZoom;

  @override
  Widget build(BuildContext context) {
    Widget imageWidget = CachedNetworkImage(
      imageUrl: imageUrl,
      width: width,
      height: height,
      fit: fit,
      alignment: alignment,
      repeat: repeat,
      matchTextDirection: matchTextDirection,
      useOldImageOnUrlChange: useOldImageOnUrlChange,
      color: color,
      colorBlendMode: colorBlendMode,
      filterQuality: filterQuality,
      memCacheWidth: width?.round(),
      memCacheHeight: height?.round(),
      cacheKey: cacheKey,
      httpHeaders: headers,
      fadeInDuration: fadeInDuration,
      fadeOutDuration: fadeOutDuration,
      placeholderFadeInDuration: placeholderFadeInDuration,
      placeholder: (context, url) => placeholder ?? _buildDefaultPlaceholder(context),
      errorWidget: (context, url, error) => errorWidget ?? _buildDefaultError(context),
    );

    if (borderRadius != null) {
      imageWidget = ClipRRect(
        borderRadius: borderRadius!,
        child: imageWidget,
      );
    }

    if (shape == BoxShape.circle) {
      imageWidget = ClipOval(child: imageWidget);
    }

    if (enableHero) {
      imageWidget = Hero(
        tag: heroTag ?? imageUrl,
        child: imageWidget,
      );
    }

    if (onTap != null || enableZoom) {
      imageWidget = GestureDetector(
        onTap: onTap ?? (enableZoom ? () => _showImageZoom(context) : null),
        child: imageWidget,
      );
    }

    return imageWidget;
  }

  Widget _buildDefaultPlaceholder(BuildContext context) {
    return Container(
      width: width,
      height: height,
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.3),
        borderRadius: borderRadius,
        shape: shape,
      ),
      child: const Center(
        child: LoadingWidget(
          type: LoadingIndicatorType.circular,
          size: 20,
        ),
      ),
    );
  }

  Widget _buildDefaultError(BuildContext context) {
    return Container(
      width: width,
      height: height,
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.errorContainer.withOpacity(0.1),
        borderRadius: borderRadius,
        shape: shape,
      ),
      child: Icon(
        Icons.broken_image_outlined,
        color: Theme.of(context).colorScheme.error,
        size: (width != null && height != null) 
            ? (width! < height! ? width! * 0.3 : height! * 0.3)
            : 24,
      ),
    );
  }

  void _showImageZoom(BuildContext context) {
    SmartDialog.show(
      builder: (context) => InteractiveViewer(
        child: CachedNetworkImage(
          imageUrl: imageUrl,
          fit: BoxFit.contain,
        ),
      ),
      backType: SmartBackType.normal,
      clickMaskDismiss: true,
    );
  }
}

/// 头像组件
class AvatarImage extends StatelessWidget {
  const AvatarImage({
    super.key,
    required this.imageUrl,
    this.size = 40,
    this.placeholder,
    this.errorWidget,
    this.backgroundColor,
    this.borderColor,
    this.borderWidth = 0,
    this.onTap,
    this.enableHero = false,
    this.heroTag,
    this.badge,
    this.badgePosition = BadgePosition.topRight,
  });

  final String imageUrl;
  final double size;
  final Widget? placeholder;
  final Widget? errorWidget;
  final Color? backgroundColor;
  final Color? borderColor;
  final double borderWidth;
  final VoidCallback? onTap;
  final bool enableHero;
  final String? heroTag;
  final Widget? badge;
  final BadgePosition badgePosition;

  @override
  Widget build(BuildContext context) {
    Widget avatar = AdvancedImage(
      imageUrl: imageUrl,
      width: size,
      height: size,
      shape: BoxShape.circle,
      placeholder: placeholder,
      errorWidget: errorWidget,
      enableHero: enableHero,
      heroTag: heroTag,
      onTap: onTap,
    );

    if (borderWidth > 0) {
      avatar = Container(
        width: size + borderWidth * 2,
        height: size + borderWidth * 2,
        decoration: BoxDecoration(
          color: borderColor ?? Theme.of(context).colorScheme.outline,
          shape: BoxShape.circle,
        ),
        child: Center(child: avatar),
      );
    }

    if (badge != null) {
      avatar = Stack(
        clipBehavior: Clip.none,
        children: [
          avatar,
          Positioned(
            top: badgePosition == BadgePosition.topLeft || badgePosition == BadgePosition.topRight ? 0 : null,
            bottom: badgePosition == BadgePosition.bottomLeft || badgePosition == BadgePosition.bottomRight ? 0 : null,
            left: badgePosition == BadgePosition.topLeft || badgePosition == BadgePosition.bottomLeft ? 0 : null,
            right: badgePosition == BadgePosition.topRight || badgePosition == BadgePosition.bottomRight ? 0 : null,
            child: badge!,
          ),
        ],
      );
    }

    return avatar;
  }
}

enum BadgePosition { topLeft, topRight, bottomLeft, bottomRight }

/// 自适应文本组件
/// 封装auto_size_text，提供智能文本大小调整
class AdvancedText extends StatelessWidget {
  const AdvancedText(
    this.text, {
    super.key,
    this.style,
    this.minFontSize = 12,
    this.maxFontSize = double.infinity,
    this.stepGranularity = 1,
    this.presetFontSizes,
    this.group,
    this.textAlign,
    this.textDirection,
    this.locale,
    this.softWrap,
    this.wrapWords = true,
    this.overflow,
    this.overflowReplacement,
    this.textScaleFactor,
    this.maxLines,
    this.semanticsLabel,
    this.textWidthBasis,
    this.textHeightBehavior,
    this.enableSelection = false,
    this.gradient,
  });

  final String text;
  final TextStyle? style;
  final double minFontSize;
  final double maxFontSize;
  final double stepGranularity;
  final List<double>? presetFontSizes;
  final AutoSizeGroup? group;
  final TextAlign? textAlign;
  final TextDirection? textDirection;
  final Locale? locale;
  final bool? softWrap;
  final bool wrapWords;
  final TextOverflow? overflow;
  final Widget? overflowReplacement;
  final double? textScaleFactor;
  final int? maxLines;
  final String? semanticsLabel;
  final TextWidthBasis? textWidthBasis;
  final TextHeightBehavior? textHeightBehavior;
  final bool enableSelection;
  final Gradient? gradient;

  @override
  Widget build(BuildContext context) {
    Widget textWidget = AutoSizeText(
      text,
      style: style,
      minFontSize: minFontSize,
      maxFontSize: maxFontSize,
      stepGranularity: stepGranularity,
      presetFontSizes: presetFontSizes,
      group: group,
      textAlign: textAlign,
      textDirection: textDirection,
      locale: locale,
      softWrap: softWrap,
      wrapWords: wrapWords,
      overflow: overflow,
      overflowReplacement: overflowReplacement,
      textScaleFactor: textScaleFactor,
      maxLines: maxLines,
      semanticsLabel: semanticsLabel,
    );

    if (gradient != null) {
      textWidget = ShaderMask(
        shaderCallback: (bounds) => gradient!.createShader(bounds),
        child: textWidget,
      );
    }

    if (enableSelection) {
      textWidget = SelectableText.rich(
        TextSpan(text: text, style: style),
        textAlign: textAlign,
        textDirection: textDirection,
        maxLines: maxLines,
      );
    }

    return textWidget;
  }
}

/// SVG图标组件
/// 封装flutter_svg，提供统一的SVG图标体验
class SvgIcon extends StatelessWidget {
  const SvgIcon({
    super.key,
    required this.assetName,
    this.size = 24,
    this.width,
    this.height,
    this.color,
    this.fit = BoxFit.contain,
    this.alignment = Alignment.center,
    this.matchTextDirection = false,
    this.allowDrawingOutsideViewBox = false,
    this.placeholderBuilder,
    this.semanticsLabel,
    this.excludeFromSemantics = false,
    this.clipBehavior = Clip.hardEdge,
    this.colorFilter,
  });

  final String assetName;
  final double size;
  final double? width;
  final double? height;
  final Color? color;
  final BoxFit fit;
  final Alignment alignment;
  final bool matchTextDirection;
  final bool allowDrawingOutsideViewBox;
  final WidgetBuilder? placeholderBuilder;
  final String? semanticsLabel;
  final bool excludeFromSemantics;
  final Clip clipBehavior;
  final ColorFilter? colorFilter;

  @override
  Widget build(BuildContext context) {
    return SvgPicture.asset(
      assetName,
      width: width ?? size,
      height: height ?? size,
      colorFilter: colorFilter ?? (color != null ? ColorFilter.mode(color!, BlendMode.srcIn) : null),
      fit: fit,
      alignment: alignment,
      matchTextDirection: matchTextDirection,
      allowDrawingOutsideViewBox: allowDrawingOutsideViewBox,
      placeholderBuilder: placeholderBuilder,
      semanticsLabel: semanticsLabel,
      excludeFromSemantics: excludeFromSemantics,
      clipBehavior: clipBehavior,
    );
  }
}

/// 网络SVG图标组件
class NetworkSvgIcon extends StatelessWidget {
  const NetworkSvgIcon({
    super.key,
    required this.url,
    this.size = 24,
    this.width,
    this.height,
    this.color,
    this.fit = BoxFit.contain,
    this.alignment = Alignment.center,
    this.matchTextDirection = false,
    this.allowDrawingOutsideViewBox = false,
    this.placeholderBuilder,
    this.semanticsLabel,
    this.excludeFromSemantics = false,
    this.clipBehavior = Clip.hardEdge,
    this.colorFilter,
    this.headers,
  });

  final String url;
  final double size;
  final double? width;
  final double? height;
  final Color? color;
  final BoxFit fit;
  final Alignment alignment;
  final bool matchTextDirection;
  final bool allowDrawingOutsideViewBox;
  final WidgetBuilder? placeholderBuilder;
  final String? semanticsLabel;
  final bool excludeFromSemantics;
  final Clip clipBehavior;
  final ColorFilter? colorFilter;
  final Map<String, String>? headers;

  @override
  Widget build(BuildContext context) {
    return SvgPicture.network(
      url,
      width: width ?? size,
      height: height ?? size,
      colorFilter: colorFilter ?? (color != null ? ColorFilter.mode(color!, BlendMode.srcIn) : null),
      fit: fit,
      alignment: alignment,
      matchTextDirection: matchTextDirection,
      allowDrawingOutsideViewBox: allowDrawingOutsideViewBox,
      placeholderBuilder: placeholderBuilder,
      semanticsLabel: semanticsLabel,
      excludeFromSemantics: excludeFromSemantics,
      clipBehavior: clipBehavior,
      headers: headers,
    );
  }
}

/// 智能弹窗组件
/// 封装flutter_smart_dialog，提供统一的弹窗体验
class SmartDialogs {
  
  /// 显示加载弹窗
  static void showLoading({
    String message = '加载中...',
    bool clickMaskDismiss = false,
    Duration displayTime = const Duration(milliseconds: 500),
  }) {
    SmartDialog.showLoading(
      msg: message,
      clickMaskDismiss: clickMaskDismiss,
      displayTime: displayTime,
    );
  }

  /// 隐藏加载弹窗
  static Future<void> dismiss() async {
    await SmartDialog.dismiss();
  }

  /// 显示吐司消息
  static void showToast({
    required String message,
    Duration displayTime = const Duration(seconds: 2),
    SmartDialogController? controller,
    Alignment alignment = Alignment.center,
  }) {
    SmartDialog.showToast(
      message,
      displayTime: displayTime,
      controller: controller,
      alignment: alignment,
    );
  }

  /// 显示成功提示
  static void showSuccess({
    required String message,
    Duration displayTime = const Duration(seconds: 2),
    Alignment alignment = Alignment.center,
  }) {
    SmartDialog.show(
      builder: (context) => Container(
        padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
        decoration: BoxDecoration(
          color: Theme.of(context).colorScheme.primaryContainer,
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.check_circle,
              color: Theme.of(context).colorScheme.primary,
              size: 20,
            ),
            const Gap(8),
            Text(
              message,
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                color: Theme.of(context).colorScheme.onPrimaryContainer,
              ),
            ),
          ],
        ),
      ),
      alignment: alignment,
      displayTime: displayTime,
    );
  }

  /// 显示错误提示
  static void showError({
    required String message,
    Duration displayTime = const Duration(seconds: 3),
    Alignment alignment = Alignment.center,
  }) {
    SmartDialog.show(
      builder: (context) => Container(
        padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
        decoration: BoxDecoration(
          color: Theme.of(context).colorScheme.errorContainer,
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.error,
              color: Theme.of(context).colorScheme.error,
              size: 20,
            ),
            const Gap(8),
            Flexible(
              child: Text(
                message,
                style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                  color: Theme.of(context).colorScheme.onErrorContainer,
                ),
              ),
            ),
          ],
        ),
      ),
      alignment: alignment,
      displayTime: displayTime,
    );
  }

  /// 显示警告提示
  static void showWarning({
    required String message,
    Duration displayTime = const Duration(seconds: 2),
    Alignment alignment = Alignment.center,
  }) {
    SmartDialog.show(
      builder: (context) => Container(
        padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
        decoration: BoxDecoration(
          color: Theme.of(context).colorScheme.secondaryContainer,
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.warning,
              color: Theme.of(context).colorScheme.onSecondaryContainer,
              size: 20,
            ),
            const Gap(8),
            Text(
              message,
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                color: Theme.of(context).colorScheme.onSecondaryContainer,
              ),
            ),
          ],
        ),
      ),
      alignment: alignment,
      displayTime: displayTime,
    );
  }

  /// 显示确认对话框
  static Future<bool> showConfirm({
    required String title,
    required String content,
    String confirmText = '确定',
    String cancelText = '取消',
    bool barrierDismissible = true,
  }) async {
    bool? result = await SmartDialog.show<bool>(
      builder: (context) => AlertDialog(
        title: Text(title),
        content: Text(content),
        actions: [
          TextButton(
            onPressed: () => SmartDialog.dismiss(result: false),
            child: Text(cancelText),
          ),
          ElevatedButton(
            onPressed: () => SmartDialog.dismiss(result: true),
            child: Text(confirmText),
          ),
        ],
      ),
      backType: SmartBackType.normal,
      clickMaskDismiss: barrierDismissible,
    );
    
    return result ?? false;
  }
}

/// 间距组件工具
/// 基于gap包的统一间距组件
class Gaps {
  // 水平间距
  static const Gap h4 = Gap(4);
  static const Gap h8 = Gap(8);
  static const Gap h12 = Gap(12);
  static const Gap h16 = Gap(16);
  static const Gap h20 = Gap(20);
  static const Gap h24 = Gap(24);
  static const Gap h32 = Gap(32);
  static const Gap h48 = Gap(48);

  // 垂直间距
  static const Gap v4 = Gap(4);
  static const Gap v8 = Gap(8);
  static const Gap v12 = Gap(12);
  static const Gap v16 = Gap(16);
  static const Gap v20 = Gap(20);
  static const Gap v24 = Gap(24);
  static const Gap v32 = Gap(32);
  static const Gap v48 = Gap(48);

  /// 创建自定义间距
  static Gap custom(double size) => Gap(size);

  /// 创建响应式间距
  static Gap responsive(BuildContext context, {
    double small = 8,
    double medium = 16,
    double large = 24,
  }) {
    final screenWidth = MediaQuery.of(context).size.width;
    if (screenWidth < 600) return Gap(small);
    if (screenWidth < 1200) return Gap(medium);
    return Gap(large);
  }
}